package org.mx.service.rocketmq;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

@SuppressWarnings("javadoc")
public class AsyncProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("rocket-mq-test1");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);
        for (int i = 0; i < 100; i ++) {
            final int index = i;
            Message msg = new Message("topic-test1", "async", "order-188",
                    "Hello world".getBytes("utf-8"));
            msg.putUserProperty("id", "" + i);
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(String.format("%-10d OK %s \n", index, sendResult.getMsgId()));
                }

                @Override
                public void onException(Throwable e) {
                    System.out.println(String.format("%-10d Exception %s \n", index, e));
                    e.printStackTrace();
                }
            });
        }
        Thread.sleep(5000);
        producer.shutdown();
    }
}
